package com.seed.util;

import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.query.QueryColumn;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.QueryTable;
import com.mybatisflex.core.row.Row;
import com.seed.core.pojo.seed.Habtms;

import java.util.Map;

public class HabtmKit {

    public static QueryCondition getThroughQueryCondition(Habtms habtm, Row self) {
        QueryTable throughTable = new QueryTable(habtm.throughTableName());
        String inferTargetColumn = habtm.inferTargetColumn();

        String selfField = StrUtil.toCamelCase(habtm.inferSelfColumn());
        QueryCondition ret = new QueryColumn(throughTable, inferTargetColumn).eq(self.get(selfField));
        Map<String, Object> extra = SeedKit.formatExtra(habtm.getExtraSeed(), habtm.getExtra());
        for(Map.Entry<String, Object> entry: extra.entrySet()) {
            ret.and(new QueryColumn(throughTable, entry.getKey()).eq(entry.getValue()));
        }

        return ret;
    }

    public static QueryCondition getSelfQueryCondition(Habtms habtm, String selfTableAlias, String throughAlias) {
        QueryTable selfTable = new QueryTable(habtm.selfSeed().getTableName()).as(selfTableAlias);
        QueryTable throughTable = new QueryTable(habtm.getThroughSeed().getTableName()).as(throughAlias);
        String inferSelfColumn = habtm.inferSelfColumn();
        String inferThroughSelfColumn = habtm.inferThroughSelfColumn();

        QueryCondition ret = new QueryColumn(throughTable, inferThroughSelfColumn)
                .eq(new QueryColumn(selfTable, inferSelfColumn));
        Map<String, Object> extra = SeedKit.formatExtra(habtm.getExtraSeed(), habtm.getExtra());
        for(Map.Entry<String, Object> entry: extra.entrySet()) {
            ret.and(new QueryColumn(throughTable, entry.getKey()).eq(entry.getValue()));
        }

        return ret;
    }

    public static QueryCondition getTargetQueryCondition(Habtms habtm, String targetTableAlias, String throughAlias) {
        QueryTable targetTable = new QueryTable(habtm.targetSeed().getTableName()).as(targetTableAlias);
        QueryTable throughTable = new QueryTable(habtm.getThroughSeed().getTableName()).as(throughAlias);
        String inferTargetColumn = habtm.inferTargetColumn();
        String inferThroughTargetColumn = habtm.inferThroughTargetColumn();

        QueryCondition ret = new QueryColumn(throughTable, inferThroughTargetColumn)
                .eq(new QueryColumn(targetTable, inferTargetColumn));
        Map<String, Object> extra = SeedKit.formatExtra(habtm.getExtraSeed(), habtm.getExtra());
        for(Map.Entry<String, Object> entry: extra.entrySet()) {
            ret.and(new QueryColumn(throughTable, entry.getKey()).eq(entry.getValue()));
        }

        return ret;
    }
}
